﻿'use strict';
app.controller('GetHelpController',
    [
    '$rootScope',
    '$scope',
    '$localStorage',
    '$state',
    '$modal',
    '$http',
    'commonFactory',
    'PinManageFactory',
function ($rootScope, $scope, $localStorage, $state, $modal,$http, commonFactory, PinManageFactory) {
    $scope.title = "GH",
    $scope.messeger = "",
    $scope.params = "",
    $scope.params2 = "",
    $scope.showProvideOrder = false,
    $scope.popup = function (windowClass, StyleModal, Controller, size, params, params2) {
        $modal.open({
            windowClass: windowClass,
            templateUrl: StyleModal,
            controller: Controller,
            size: size,
            resolve: {
                messeger: function () {
                    return $scope.messeger;
                },
                title: function () {
                    return $scope.title;
                },
                params: function () {
                    $scope.params = params;
                    return $scope.params;
                },
                params2: function () {
                    $scope.params2 = params2;
                    return $scope.params2;
                },
            }
        })
    },
    $scope.List = [],
    $scope.doConfirm = function (Id) {
        //2:Confirm
        commonFactory.confirmTransferOrder(Id,2).then(function (rsp) {
            if (rsp.data.Status) {
                window.location.reload();
            } else {
                $scope.messeger = rsp.data.Msg,
                $scope.title = 'Warning',
                $scope.popup('modal-message modal-warning', "WarningModal");
            }
        }, function (error) {
            $scope.status = 'Unable to load profile data: ' + error.message;
        });
    },
    GetListGH($localStorage.user.UserId);
    function GetListGH(userId) {
        commonFactory.getListGH(userId).then(function (rsp) {
            if (rsp.data.Status) {
                $scope.List = rsp.data.Result;
            } else {
                $scope.messeger = rsp.data.Msg;
            }
        });
    };
 }
]);

app.controller('ProvideHelpController',
    [
    '$rootScope',
    '$scope',
    '$localStorage',
    '$state',
    '$modal',
    '$confirm',
    '$filter',
    'commonFactory',
    'PinManageFactory',
function ($rootScope, $scope, $localStorage, $state, $modal, $confirm, $filter, commonFactory, PinManageFactory) {
    $scope.title = "Provide Help",
    $scope.messeger = "",
    $scope.params = "",
    $scope.params2 = "",
    $scope.showOrder = false,//hide/show Order 
    $scope.pinPH = "",
    $scope.popup = function (windowClass, StyleModal, Controller, size, params,params2) {
        $modal.open({
            windowClass: windowClass,
            templateUrl: StyleModal,
            controller: Controller,
            size: size,
            resolve: {
                messeger: function () {
                    return $scope.messeger;
                },
                title: function () {
                    return $scope.title;
                }, params: function () {
                    $scope.params = params;
                    return $scope.params;
                }, params2: function () {
                    $scope.params2 = params2;
                    return $scope.params2;
                },
            }
        })
    },
    $scope.List = [],
    $scope.PHList = [],
    $scope.pushPin = function (pinPH) {
        if (pinPH != 'undefined' && pinPH != "")
        {
            PushPin($localStorage.user.UserId, pinPH);
        } else {
            $scope.messeger = "Pin not enough";
        }
    },
    GetListPH($localStorage.user.UserId);
    GetPinForPH($localStorage.user.UserId);
    function GetListPH(UserId) {
        commonFactory.getListPH(UserId).then(
             function successCallback(resp) {
                 if (resp.data.Status) {
                     $scope.List = resp.data.Result;
                 } else
                     $scope.messeger = resp.data.Msg;
             }, function errorCallback(resp) {
                 $scope.messeger = "";
             })
    };
    function GetPinForPH(userId) {
        commonFactory.getPinForPH(userId).then(
             function successCallback(resp) {
                 if (resp.data.Status) {
                     $scope.pinPH = resp.data.Result;
                 }
             }, function errorCallback(resp) {
                 $scope.messeger = "";
             })
    };
    function PushPin(userId, pinPH) {
        commonFactory.pushPin(userId, pinPH).then(
             function successCallback(resp) {
                 if (resp.data.Status) {
                     $scope.messeger = resp.data.Msg;
                     $scope.AlertType = "Provide Help(PH) Success !!!";
                     setTimeout(location.reload(), 6000);
                 }
             }, function errorCallback(resp) {
                 $scope.messeger = resp.data.Msg;
                 $scope.AlertType = "danger";
             })
    };
  }
]);

app.controller('ModalInstanceCtrl', function ($scope, $modalInstance, messeger, title) {
    $scope.messeger = messeger,
    $scope.title = title;
    $scope.ok = function () {
        $modalInstance.close();
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
});
app.controller('CashoutModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $timeout, $state, $stateParams, messeger, title, params, params2, commonFactory, WalletFactory) {

    $scope.messeger = messeger,
    $scope.title = title,
    $scope.processing = false,
    $scope.AlertType = "warning";
    $scope.payment = {},
    $scope.wallet = {},
    $scope.PaymentMethod = [],
    $scope.selected = [],
    $scope.FeeConfig = {},
    $scope.data = { Amount: "", Fee: 0, After: 0,Balance:""};
    //get fee cashout dynamit
    $scope.doProcess = function (data) {
        $scope.messeger = "";
        if (parseFloat(data.Amount) > 0.005) {
            $scope.data.After = data.Amount - (data.Amount * data.Fee);
        } else if (parseFloat(data.Amount) > parseFloat(data.Balance))
        {
            $scope.messeger = "Amount must greater balance";
        }
        else {
            $scope.data.After = 0;
            $scope.messeger = "Amount must greater > 0.005";
        }
    },
    $scope.doCashout = function (item) {
        $scope.processing = true,
        $scope.ExistSession = false,
        $scope.messeger = "";
        if (item.Amount > 0 && item.PaymentId > 0) {
            commonFactory.CheckSession($localStorage.user.SessionId).then(function (resp) {
                if (resp.data.Status) {
                    //do prosess
                    Cashout(item);
                    $modalInstance.close();
                    window.location.reload();
                } else {
                    $localStorage.user = null;
                    $scope.messeger = "Session is expired";
                    $timeout(function () {
                        $state.go('login');
                    }, 5000);
                }
            }, function (error) {
                $scope.status = 'Unable to check session data: ' + error.message;
            });

        } else {
            $scope.processing = false,
            $scope.messeger = "Error: Amount >= 0,";
        }
    },
    GetWalletDefault($localStorage.user.UserId),
    GetPaymentMethod(),
    getFeeConfig(),
    $scope.ok = function () {
        $modalInstance.close();
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    function GetWalletDefault(UserID) {
        commonFactory.getWalletDefault(UserID).then(function (rsp) {
            $scope.data.Balance = 'Default Wallet: ฿ ' + rsp.data.wallet.Balance;
        }, function (error) {
            $scope.status = error.message;
        });
    };
    function GetPaymentMethod() {
        commonFactory.GetPaymentMethod().then(function (response) {
            $scope.PaymentMethod = response.data.Result;
        }, function (error) {
            $scope.status = 'Unable to load profile data: ' + error.message;
        });
    };
    function getFeeConfig() {
        WalletFactory.getFeeConfig().then(function (response) {
            $scope.data.Fee = response.data.Result.Cashout;
        }, function (error) {
            $scope.status = 'Unable to load profile data: ' + error.message;
        });
    };

    function Cashout(item) {
        $http.post($rootScope.APITransactionUrl + 'CashOutNotApprove', {
            userid: $localStorage.user.UserId,
            amount: item.Amount,
            payment: item.PaymentId,
            walletId: 1
        }).then(function(rsp) {
            $scope.processing = false;
            if (rsp.data.Status) {
                $scope.AlertType = "success";
            } else {
                $scope.AlertType = "warning";
            }
            $scope.messeger = resp.data.Messeger;
        })
    };

});
app.controller('TransactionModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $timeout, $state, $stateParams, messeger, title, params,params2, commonFactory)
{
    $scope.messeger = messeger,
    $scope.title = title,
    $scope.withdrawID = params,
    $scope.data = { usersend: "", transactioncode: "", createdate: "" },
    GetTransactionByWithdraw($scope.withdrawID),
    $scope.ok = function () {
        $modalInstance.close();
    };
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    function GetTransactionByWithdraw(withdrawID)
    {
        commonFactory.getTransactionByWithdraw(withdrawID).then(function (rsp)
        {
            $scope.data.usersend = rsp.data.FromUser;
            $scope.data.transactioncode = rsp.data.Code;
            $scope.data.createdate = rsp.data.CreateDate;
        }, function (error) {
            $scope.status = error.message;
        });
    }
});
app.controller('AddOrderModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $timeout, $state, $stateParams, messeger, title, commonFactory, BitcoinFactory) {
    $scope.messeger = messeger,
        $scope.title = title,
        $scope.package = {},
        $scope.AmountList = [],
        $scope.data = { Amount: 0, PinCode: "" },
        $scope.rate = 0,
        GetListPackage(),
        GetBitcointoUSDRate(1),
        $scope.doAddOrder = function (data) {
            AddOrderNotProfit(data);
        },
        $scope.ok = function () {
            $modalInstance.close();
        };
     
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
        function GetListPackage() {
            commonFactory.getListPackage().then(function (rsp) {
                $scope.AmountList = rsp.data.Result;
            }, function (error) {
                $scope.status = error.message;
            });
        }
        function AddOrderNotProfit(data) {
            commonFactory.addOrderNotProfit($localStorage.user.UserId, data.Amount, data.PinCode).then(function (rsp) {
                if (rsp.data.Status) {
                    $modalInstance.close();
                    window.location.reload();
                } else {
                    $scope.messeger = rsp.data.Msg;
                }

            }, function (error) {
                $scope.status = error.message;
            });
        };
        function GetBitcointoUSDRate(Bitcoin) {
            BitcoinFactory.GetBitcointoUSDRate(Bitcoin).then(function (response) {
                $scope.rate = response.data;
            }, function (error) {
                $scope.status = 'Unable to load rate data: ' + error.message;
            });
        };
});
app.controller('PHViewModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $state, $stateParams, messeger, title, params,params2, commonFactory) {
    $scope.messeger = messeger,
    $scope.title = title,
    $scope.processing = false,
    $scope.AlertType = "warning";
    $scope.user = {},
    $scope.parent = {},
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    },
    GetUserByID(params);
    GetParentByID(params);
    GetConfirmTransferPH(params2);
    function GetUserByID(userId){
        commonFactory.getUserById(userId).then(function (rsp) {
                $scope.user = rsp.data;

        }, function (error) {
            $scope.status = error.message;
        });
    };
    function GetParentByID(userId) {
        commonFactory.getParentById(userId).then(function (rsp)
        {
            if(rsp.data.Status)
            {
                $scope.parent = rsp.data.Result;
            }

        }, function (error) {
            $scope.status = error.message;
        });
    };
    function GetConfirmTransferPH(transId) {
        commonFactory.getConfirmTransferPH(transId).then(function (rsp) {
            if (rsp.data.Status) {
                if (rsp.data.Result != null)
                    {
                    $scope.imagePH = $rootScope.API + rsp.data.Result.Image;
                }
            }

        }, function (error) {
            $scope.status = error.message;
        });
    };
});
app.controller('GHViewModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $state, $stateParams, messeger, title, params,params2, commonFactory) {
    $scope.messeger = messeger,
    $scope.title = title,
    $scope.processing = false,
    $scope.AlertType = "warning",
    $scope.imagePH = "",
    $scope.user = {},
    $scope.parent = {},
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    },
    GetConfirmTransferPH(params2),
    GetUserByID(params);
    GetParentByID(params);
    function GetUserByID(userId) {
        commonFactory.getUserById(userId).then(function (rsp) {
            $scope.user = rsp.data;

        }, function (error) {
            $scope.status = error.message;
        });
    };
    function GetParentByID(userId) {
        commonFactory.getParentById(userId).then(function (rsp) {
            if (rsp.data.Status) {
                $scope.parent = rsp.data.Result;
            }

        }, function (error) {
            $scope.status = error.message;
        });
    };
    function GetConfirmTransferPH(transId) {
        commonFactory.getConfirmTransferPH(transId).then(function (rsp) {
            if (rsp.data.Status) {
                if (rsp.data.Result != null) {
                    $scope.imagePH = $rootScope.API + rsp.data.Result.Image;
                }
            }

        }, function (error) {
            $scope.status = error.message;
        });
    };
});
app.controller('ReportPHModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $state, $stateParams, messeger, title, params,params2, commonFactory) {
    $scope.messeger = messeger,
    $scope.title = title,
    $scope.processing = false,
    $scope.AlertType = "warning";
    $scope.trans = {},
    $scope.actiontype = {},
    $scope.selected = [],
    $scope.badtype = [{
        'Type': 0,
        'Name': 'Change PH'
    }, {
        'Type': 1,
        'Name': 'Use Risk Wallet'
    }],
    $scope.actiontype.selected = { Name: 'Change PH', Id: 0 },
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    },
    $scope.doReport = function(Id,desc,actionType)
    {
        commonFactory.createBadReport(Id, 0, desc, actionType).then(function (rsp) {
            if (rsp.data.Status) {
                $scope.messeger = rsp.data.Msg;
                setTimeout(location.reload(), 3000);
            } else
                $scope.messeger = rsp.data.Msg;

        }, function (error) {
            $scope.status = error.message;
        });
    },
    FindTransferOrderById(params);
    function FindTransferOrderById(transId) {
        commonFactory.findTransferOrderById(transId).then(function (rsp) {
            if (rsp.data.Status) {
                $scope.trans = rsp.data.Result;
            } else
                $scope.messeger = rsp.data.Msg;

        }, function (error) {
            $scope.status = error.message;
        });
    };
});
app.controller('ReportGHModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $state, $stateParams, messeger, title, params, commonFactory, upload) {
    $scope.messeger = messeger,
    $scope.title = title,
    $scope.processing = false,
    $scope.AlertType = "warning";
    $scope.trans = {},
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    },
    $scope.doReport = function (Id, desc) {
        commonFactory.createBadReport(Id, 1, desc).then(function (rsp) {
            if (rsp.data.Status) {
                $scope.messeger = rsp.data.Msg;
                setTimeout(location.reload(), 3000);
            } else
                $scope.messeger = rsp.data.Msg;

        }, function (error) {
            $scope.status = error.message;
        });
    },
    FindTransferOrderById(params);
    function FindTransferOrderById(transId) {
        commonFactory.findTransferOrderById(transId).then(function (rsp) {
            if (rsp.data.Status) {
                $scope.trans = rsp.data.Result;
            } else
                $scope.messeger = rsp.data.Msg;

        }, function (error) {
            $scope.status = error.message;
        });
    };
});
app.controller('ConfirmTransferPHModalInstanceCtrl', function ($scope, $modalInstance, $localStorage, $http, $rootScope, $state, $stateParams, messeger, title, params, commonFactory) {
    $scope.messeger = messeger,
    $scope.title = title,
    $scope.processing = false,
    $scope.AlertType = "warning";
    $scope.trans = {},
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    },
    $scope.doConfirm = function (desc2) {
        var files = document.getElementById('myfile').files;
        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                }
                $.ajax({
                    type: "POST",
                    url: $rootScope.API + 'JsonTransaction/' + '/confirmTransferPH?transId=' + params + '&desc=' + desc2,
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {                        
                        $('#msg').html('Success !!!');
                    },
                    error: function (xhr, status, p3, p4) {
                        var err = "Error " + " " + status + " " + p3 + " " + p4;
                        if (xhr.responseText && xhr.responseText[0] == "{")
                            err = JSON.parse(xhr.responseText).Message;
                        console.log(err);
                    }
                });
            } else {
                alert("This browser doesn't support HTML5 file uploads!");
            }
        }
    };
});

